﻿using System;
using System.Collections.Generic;
using SmartMotion.Core.Mgrs;

namespace SmartMotion.Core
{
    public class SetField : FieldBase
    {
        protected override ActionResult RunMethod()
        {
            try
            {
                Initilize();

                #region 读属性的对象

                Obj = null;
                if (!string.IsNullOrEmpty(ObjName))
                {
                    VarInfo varInfo = VarMgr.Ins.GetVarByGuid(ObjGuid);
                    Obj = varInfo.Value;
                }

                #endregion 读属性的对象

                #region 参数数组对象

                var objs = new List<object>();
                for (var index = 0; index < Parms.Count; index++)
                {
                    var item = Parms[index];
                    object temp;

                    //取出变量
                    VarInfo varInfo = VarMgr.Ins.GetVarByName(item.VarName);

                    if (varInfo != null)
                    {
                        temp = varInfo.Value;
                    }
                    else
                    {
                        var valueType = Type.GetType(ParaTypes[index]);
                        if (valueType == typeof(int)) temp = Convert.ToInt32(item.VarName);
                        else if (valueType == typeof(uint)) temp = Convert.ToUInt32(item.VarName);
                        else if (valueType == typeof(bool)) temp = Convert.ToBoolean(item.VarName);
                        else if (valueType == typeof(short)) temp = Convert.ToInt16(item.VarName);
                        else if (valueType == typeof(ushort)) temp = Convert.ToUInt16(item.VarName);
                        else if (valueType == typeof(long)) temp = Convert.ToInt64(item.VarName);
                        else if (valueType == typeof(ulong)) temp = Convert.ToUInt64(item.VarName);
                        else if (valueType == typeof(float)) temp = Convert.ToSingle(item.VarName);
                        else if (valueType == typeof(double)) temp = Convert.ToDouble(item.VarName);
                        else
                        {
                            temp = item.VarName;
                        }
                    }
                    if (temp != null) objs.Add(temp);
                }

                #endregion 参数数组对象

                _fieldInfo.SetValue(Obj, objs[0]);

                return ActionResult.Success;
            }
            catch (Exception e)
            {
                Em.GetEvent<DebugMessage>().Publish($"运行{ItemName}时出现异常:{e.Message}");
                return ActionResult.Error;
            }
        }
    }
}
